<template>
  <div>
    <PostCreate />
    
    <div v-if="loading" class="text-center py-8">
      <Loading />
    </div>
    
    <div v-else-if="posts.length === 0" class="text-center py-8 text-gray-500">
      暂无帖子
    </div>
    
    <div v-else>
      <PostItem 
        v-for="post in posts" 
        :key="post.id" 
        :post="post" 
        @like="handleLike"
        @comment="handleComment"
      />
    </div>
    
    <div v-if="hasMore && !loading" class="text-center py-6">
      <button 
        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-md transition duration-300"
        @click="loadMore"
      >
        加载更多
      </button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { usePostStore } from '@/store/modules/post'
import PostCreate from './PostCreate.vue'
import PostItem from './PostItem.vue'
import Loading from '@/components/common/Loading.vue'

export default {
  components: {
    PostCreate,
    PostItem,
    Loading
  },
  
  setup() {
    const postStore = usePostStore()
    
    const posts = computed(() => postStore.posts)
    const loading = computed(() => postStore.loading)
    const hasMore = computed(() => postStore.hasMore)
    
    onMounted(async () => {
      await postStore.fetchPosts()
    })
    
    const loadMore = async () => {
      if (loading.value || !hasMore.value) return
      await postStore.fetchMorePosts()
    }
    
    const handleLike = async (postId) => {
      try {
        await postStore.toggleLike(postId)
      } catch (error) {
        console.error('Error liking post:', error)
      }
    }
    
    const handleComment = async (postId, content) => {
      try {
        await postStore.addComment(postId, content)
      } catch (error) {
        console.error('Error adding comment:', error)
      }
    }
    
    return {
      posts,
      loading,
      hasMore,
      loadMore,
      handleLike,
      handleComment
    }
  }
}
</script>